<template>
  <div class="app-container">
    <div class="material-add">
      <div class="material-search" />
      <div class="material-button">
        <el-button type="primary" @click="showAddForm">创建计算规则</el-button>
      </div>
    </div>
    <el-table :data="tableData" v-loading="tableLoading">
      <el-table-column label="序号" type="index" :index="indexMethod" />
      <el-table-column prop="id" label="规则ID" />
      <el-table-column prop="ruleName" label="规则名称" />
      <el-table-column prop="effectiveTime" label="宠物类型">
        <template slot-scope="scope">
          <span v-if="+scope.row.ruleContentType === 1">狗</span>
          <span v-if="+scope.row.ruleContentType === 2">猫</span>
        </template>
      </el-table-column>
      <el-table-column prop="ruleRemark" label="年龄段" />
      <el-table-column prop="coefficient" label="系数" />
      <el-table-column prop="effectiveTime" label="生效时间" />
      <el-table-column prop="uploadUser" label="创建人" />
      <el-table-column label="操作" width="200px">
        <template slot-scope="scope">
          <el-switch
            :value="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="($event) => changeSwitch($event, scope.row)" />
<!--          <el-button style="margin: 5px" @click="editItemClick(scope.row)" type="text" size="small">编辑</el-button>-->
          <el-button @click="viewItemClick(scope.row)" :style="{ marginLeft: '5px' }" type="text" size="small">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <InBody v-show="total>0">
      <pagination
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getTableData"
      />
    </InBody>
    <el-dialog title="喂食量规则" :visible.sync="dialogVisible" width="600px" @close="closeAddForm">
      <el-form
        :model="addForm"
        :rules="rules"
        label-position="right"
        label-width="auto"
        ref="addForm"
        :disabled="editDisabled">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="addForm.ruleName" placeholder="规则名称" :maxlength="20" />
        </el-form-item>
        <el-form-item label="规则内容：" />
        <el-form-item label="宠物类型" prop="ruleContentType">
          <el-select v-model="addForm.ruleContentType" placeholder="请选择计划订单时长">
            <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄段" prop="ruleContentType">
          <el-select v-model="addForm.ruleRemark" placeholder="请选择年龄段">
            <el-option v-for="item in ageList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="系数" prop="coefficient">
          <el-input-number v-model="addForm.coefficient"  :min="0" :step="0.1" :max="1" placeholder="请输入系数" />
        </el-form-item>
        <el-form-item label="生效时间" prop="effectiveTime">
          <el-date-picker
            type="datetime"
            v-model="addForm.effectiveTime"
            placeholder="生效时间"
            :picker-options="{disabledDate}" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAddForm">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { queryRulesList, saveRules, updateRules, queryRulesDetail } from '@/api/rules'
import { queryAreaData, queryAreaChildrenData } from '@/api/activity';
import moment from "moment";
import { pick } from 'lodash'

export default {
  computed: {
    ...mapGetters(['name', 'userId']),
  },
  data() {
    return {
      typeList: [
        { label: '狗', value: 1 },
        { label: '猫', value: 2 }
      ],
      ageList: [
        { label: '幼年', value: 1 },
        { label: '成年', value: 2 },
        { label: '老年', value: 3 }
      ],
      statusMap: [
        { label: '待生效', value: 0 },
        { label: '生效中', value: 1 },
        { label: '已失效', value: 2 }
      ],
      tableData: [],
      tableLoading: false,
      editDisabled: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      dialogVisible: false,
      couponList: [],
      provinceData: [],
      cityData: [],
      userTagsList: [],
      editId: '',
      addForm: {
        ruleName: '',
        ruleContentType: '',
        ruleRemark: '',
        effectiveTime: '',
        coefficient: ''
      },
      rules: {
        ruleName: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
        ruleContentType: [{ required: true, message: '请选择订单类型', trigger: 'blur' }],
        ruleRemark: [{ required: true, message: '请选择年龄段', trigger: 'blur' }],
        effectiveTime: [{ required: true, message: '请选择生效时间', trigger: 'blur' }],
        coefficient: [{ required: true, message: '请输入包邮门槛', trigger: 'blur' }]
      }
    };
  },
  mounted() {
    this.getTableData()
  },
  methods: {
    handleCopeRow (record) {
      this.$confirm('确定复制一条吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.createRow(pick(record, Object.keys(this.addForm)))
      })
        .catch()
    },
    handleUpdateFile () {
      document.getElementById('file-upload').click()
    },
    searchClick () {
      return this.getTableData();
    },
    indexMethod(index) {
      return index + 1;
    },

    async getTableData() {
      this.tableLoading = true
      const { code, rows, total } = await queryRulesList({
        ruleType: 2,
        ...this.queryParams
      })
      this.tableLoading = false
      if (code !== 200) return;
      this.total = +total
      this.tableData = rows
    },
    showAddForm() {
      this.resetFields()
      this.dialogVisible = true
    },
    resetFields () {
      Object.assign(this.$data.addForm, this.$options.data().addForm)
    },
    closeAddForm() {
      this.resetFields();
      this.editId = '';
      this.editDisabled = false
      this.dialogVisible = false;
    },

    disabledDate(date) {
      return moment().isAfter(date, 'second')
    },

    changeSwitch(event, item) {
      this.$confirm(`确定${event ? '上线' : '下线'}吗？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { code } = await this.updateRow({ id: item.id, status: event })
        if (code !== 200) return;
        this.$message({ message: `${event ? '上线' : '下线'}成功`, type: 'success' });
        return this.getTableData();
      })
        .catch()
    },
    async editItemClick(record) {
      this.editId = record.id;
      const { code, data } = await queryRulesDetail({ id: record.id })
      if (code !== 200) return;
      this.addForm = {
        ...pick(data, Object.keys(this.addForm)),
        ruleRemark: +data.ruleRemark,
        ruleContentType: +data.ruleContentType
      };
      this.dialogVisible = true;
    },
    async viewItemClick(record){
      const { code, data } = await queryRulesDetail({ id: record.id })
      if (code !== 200) return;
      this.editDisabled = true
      this.addForm = {
        ...pick(data, Object.keys(this.addForm)),
        ruleRemark: +data.ruleRemark,
        ruleContentType: +data.ruleContentType
      };
      this.dialogVisible = true;
    },
    handleSubmit() {
      if (this.editDisabled) return this.closeAddForm()
      this.$refs['addForm'].validate(async (valid) => {
        if (!valid) return;
        if (this.editId) {
          await this.updateRow({
            ...this.addForm,
            effectiveTime: this.addForm.effectiveTime ? moment(this.addForm.effectiveTime).format('YYYY-MM-DD HH:mm:ss') : '',
            createUserName: this.name,
            createUserId: this.userId
          })
        } else {
          await this.createRow({
            ...this.addForm,
            effectiveTime: moment(this.addForm.effectiveTime[0]).format('YYYY-MM-DD HH:mm:ss'),
            createUserName: this.name,
            createUserId: this.userId
          })
        }
        this.closeAddForm();
        return this.getTableData();
      })
    },
    async updateRow (params) {
      const { code } = await updateRules({
        ...params,
        createUserName: this.name,
        createUserId: this.userId
      })
      if (code !== 200) return { code };
      this.$message({ message: '修改成功', type: 'success' });
      return { code }
    },
    async createRow (params) {
      const { code } = await saveRules({
        ...params,
        ruleType: 2,
        createUserName: this.name,
        createUserId: this.userId
      })
      if (code !== 200) return;
      this.$message({ message: '添加成功', type: 'success' });
    }
  }
};
</script>
<style scoped lang="scss">
.material-add {
  width: 100%;
  height: auto;
  display: grid;
  grid-template-columns: 85% 15%;
  margin-bottom: 15px;

  div {
    &.material-search {}

    &.material-button {
      text-align: right;
    }
  }
}

.upload-container {
  width: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  text-align: center;
  overflow: hidden;
  &:hover {
    color: #409EFF;
    border-color: #409EFF;
  }
}

.custom-upload-button {
  display: inline-block;

  background-color: transparent;
  color: #46a6ff;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.custom-upload-button:hover {
  background-color: transparent;
}

.icon {
  margin-right: 10px;
}

#file-name {
  margin-top: 10px;
  font-size: 14px;
  color: #333;
}
</style>
